package btctx

import (
	"github.com/btcsuite/btcd/txscript"
	"github.com/btcsuite/btcutil"
)

func SignTx(rawtx string, wif_priv string) (string, error) {
	// 转换私钥
	wif, err := btcutil.DecodeWIF(wif_priv)
	if err != nil {
		return "", err
	}
	priv := wif.PrivKey
	// 解码交易
	tx, err := DecodeTxString(rawtx)
	if err != nil {
		return "", err
	}
	//提取pk_script
	pk_scripts := [][]byte{}
	for i := range tx.TxIn {
		pk_script := tx.TxIn[i].SignatureScript
		tx.TxIn[i].SignatureScript = nil
		pk_scripts = append(pk_scripts, pk_script)
	}
	// 开始签名
	for i := range tx.TxIn {
		txin := tx.TxIn[i]
		pk_script := pk_scripts[i]
		sig_script, err := txscript.SignatureScript(tx, i, pk_script, txscript.SigHashAll, priv, true)
		if err != nil {
			return "", err
		}
		txin.SignatureScript = sig_script
	}
	// 编码签名交易
	return EncodeTxString(tx)
}
